//
//  FWSinaAuthHandler.m
//  FWShare
//
//  Created by 范文青 on 14-6-14.
//  Copyright (c) 2014年 fwq. All rights reserved.
//

#import "FWSinaAuthHandler.h"
#import "FWAuthHandler.h"
#import "FWSinaAuthorizeParam.h"
#import "FWShare.h"
#import "FWAccountProcotol.h"
#import "NSMutableURLRequest+FWHTTPAddition.h"
#import "FWURLQuery.h"
#import "FWAccessTokenParam.h"
#import "FWAccessToken.h"
#import "FWSinaGetUserInfoParam.h"
#import "FWAuthUser.h"
#import "BBlock.h"
@interface FWSinaAuthHandler()
@end

@implementation FWSinaAuthHandler
- (FWSinaAuthorizeParam *)authParam
{
    FWSinaAuthorizeParam  *param = [FWSinaAuthorizeParam new];
    [param setClient_id:[[[FWShare shareCenter] accounts] sinaAppKey]];
    [param setRedirect_uri:[[[FWShare shareCenter] accounts] sinaRedirectUrl]];
    if (self.forceAuth) {
        [param setForcelogin:@"true"];
    }else{
        [param setForcelogin:@"false"];
    }
    return param;
}
- (FWAccessTokenParam *)accessTokenParam:(NSString *)code
{
    FWAccessTokenParam *param = [FWAccessTokenParam new];
    [param setCode:code];
    [param setClient_id:[[[FWShare shareCenter] accounts] sinaAppKey]];
    [param setClient_secret:[[[FWShare shareCenter] accounts] sinaSecrect]];
    [param setRedirect_uri:[[[FWShare shareCenter] accounts] sinaRedirectUrl]];
    return param;
}
- (FWSinaGetUserInfoParam *)userInfoParam:(FWAccessToken *)token
{
    FWSinaGetUserInfoParam *param = [FWSinaGetUserInfoParam new];
    [param setUid:token.uid];
    [param setSource:[[[FWShare shareCenter] accounts] sinaAppKey]];
    [param setAccess_token:[token access_token]];
    return param;
}

- (void)startAuth:(FWAuthViewController *)authController
{
    self.authController = authController;
    [authController.authWebView setDelegate:self];
    NSMutableURLRequest  *authRequest = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://open.weibo.cn/oauth2/authorize"] parameters:[[self authParam] dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodGET contentType:FWPostContentTypeNone];
    [authController.authWebView loadRequest:authRequest];
}

- (void)getAccessToken:(NSString *)code
{
    NSMutableURLRequest  *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://api.weibo.com/oauth2/access_token"] parameters:[[self accessTokenParam:code] dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodPOST contentType:FWPostContentTypeForm];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [BBlock dispatchOnMainThread:^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([self isValid:dic]) {
                FWAccessToken  *token = [FWAccessToken instanceSina:dic];
                long long expirtes_in = [[token expires_in] longLongValue] + [[NSDate date] timeIntervalSince1970];
                [token setExpires_in:[NSString stringWithFormat:@"%llu",expirtes_in]];
                [self getUserInfo:token];
            }
        }];
    }];
}
- (void)getUserInfo:(FWAccessToken *)accessToken
{
    NSMutableURLRequest  *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://api.weibo.com/2/users/show.json"] parameters:[[self userInfoParam:accessToken] dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodGET contentType:FWPostContentTypeNone];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [BBlock dispatchOnMainThread:^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            FWAuthUser  *user = [FWAuthUser instanceSina:dic];
            [user setToken:accessToken];
            [user save];
            if (self.authController.authSuccess) {
                self.authController.authSuccess(user,self.authController.platform);
            }
        }];
    }];
    
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = [[request URL] description];
    if ([urlString hasPrefix:[[[FWShare shareCenter] accounts] sinaRedirectUrl]]) {
        FWURLQuery  *query = [[FWURLQuery alloc] initWithURL:[request URL]];
        NSString  *code = [query get:@"code"];
        [self getAccessToken:code];
        return NO;
    }
    return YES;
}
- (BOOL)isValid:(NSDictionary *)dic{
    if ([dic objectForKey:@"error_code"] == nil) {
        return YES;
    }

    int code = [[dic objectForKey:@"error_code"] intValue];
    NSString *message = [dic objectForKey:@"error"];
    
    NSError  *error = [NSError errorWithDomain:@"FWSinaAuthFailed" code:code userInfo:@{@"message": message}];
    if (self.authController.authFailed) {
        self.authController.authFailed(error,self.authController.platform);
    }
    return NO;
}
@end
